package init

import (
	"api-getaway/basic/config"
	"api-getaway/basic/model"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

func init() {
	InitConfig()
	InitRedis()
	InitMysql()
	InitEs()
}

func InitConfig() {
	viper.SetConfigFile("../config.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("读取配置文件失败")
	}
	err = viper.Unmarshal(&config.Config)
	if err != nil {
		panic("解析配置文件失败")
	}
	fmt.Println(config.Config)
}

func InitMysql() {
	var err error
	data := config.Config.Mysql
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		data.User, data.Password, data.Host, data.Port, data.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	} else {
		fmt.Println("数据库连接成功")
	}

	err = config.DB.AutoMigrate(&model.User{}, &model.Video{}, &model.Category{}, &model.Region{}, &model.UserHistory{}, &model.Type{}, &model.DramaEpisode{}, &model.VideoReview{}, &model.Ranking{})
	if err != nil {
		panic("数据库迁移失败")
	} else {
		fmt.Println("数据库迁移成功")
	}

	sqlDB, err := config.DB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

}

func InitRedis() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	err := config.Rdb.Set(config.Ctx, "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("redis连接成功")
}

func InitEs() {
	var _ *elasticsearch.Client
	cfg := elasticsearch.Config{
		Addresses: []string{
			"http://localhost:9200",
		},
		// ...
	}
	_, err := elasticsearch.NewClient(cfg)
	if err != nil {
		return
	}
	fmt.Println("es连接成功")
}
